package controllers;

import helpers.GeneralHelper;
import helpers.PaginatorHelper;
import helpers.StringHelper;
import helpers.UrlHelper;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.cache.Cache;
import javax.script.Bindings;
import javax.script.CompiledScript;
import javax.script.ScriptContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import admin.models.MetaSeoModel;

import quercus.CompileScriptEngine;

import systems.ConfigSystem;
import systems.Recently;
import systems.RecentlyTag;

import debugs.ArticleDebug;

import entities.Ads;
import entities.Article;
import entities.Category;
import entities.MetaSeo;
import entities.SeoData;
import entities.SiteConfig;
import entities.User;

import models.ArticleModel;
import models.CategoryModel;
import models.UserModel;

public class CategoryServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
		SiteConfig config = ConfigSystem.getConfigs();
		
		String path = ((HttpServletRequest) request).getRequestURI();
		String alias = URLDecoder.decode(path.replaceAll(request.getServletPath() + "/", ""),"UTF-8");
		
		CategoryModel categoryModel = CategoryModel.getInstance();
		Category category = categoryModel.getCategoryByAlias(alias);
		
		if (category == null) {
			response.sendRedirect("/msg/page-not-found");
			return ;
		}
		
		String language = (String) request.getAttribute("language");
		if (language == null || language.isEmpty()) {
			language = "en";
		}
		
		//Get article by category and paginator
		int page = 1;
		try {
			page = Integer.parseInt((String) request.getParameter("page"));
		} catch (Exception e) {}
		
		boolean nextPage = false;
		boolean prevPage = false;
		int limit = 20;
		
		
		ArticleModel articleModel = ArticleModel.getInstance();
		List<Article> articles = Recently.getArticles(category.getId(), "category");
		
		if (page > 1) {
			articles = articleModel.listByCategory(category.getId(), page, limit, language);
		} else {
			List<Article> lsArticles = articleModel.listByCategory(category.getId(), page, limit, language);
			if (articles.size() == 0 || articles.size() < lsArticles.size()) {
				for (int i = lsArticles.size() - 1; i >= 0; i--) {
					Recently.insertArticle(category.getId(), "category", lsArticles.get(i));
				}
				articles = Recently.getArticles(category.getId(), "category");
			}
		}
		
		
		
		if (articles.size() == limit) {
			nextPage = true;
		}
		
		if (page > 1) {
			prevPage = true;
		}
		
		//Get paginate
		String queryString = request.getQueryString();
		String requestURI = request.getRequestURI();
		PaginatorHelper paginator = new PaginatorHelper(queryString);
		paginator.setUrl(requestURI);
		
		//Get categories
		List<String> uIds = new ArrayList<String>();
		
		for (int i = 0; i < articles.size(); i++) {
			if (!articles.get(i).getCreator().isEmpty()) {
				uIds.add(articles.get(i).getCreator());
			}
		}
		
		UserModel userModel = UserModel.getInstance();
		Map<String, User> authors = userModel.getByListId(uIds);
		
		MetaSeoModel metaseoModel = MetaSeoModel.getInstance();
		MetaSeo metaseo = metaseoModel.get("category");
		
		//Cache header
		response.addHeader("Cache-Control", "public, max-age=60000");
		
		request.setAttribute("category", category);
		request.setAttribute("articles", articles);
		request.setAttribute("authors", authors);
		request.setAttribute("paginator", paginator);
		request.setAttribute("prevPage", prevPage);
		request.setAttribute("nextPage", nextPage);
		request.setAttribute("page", page);
		request.setAttribute("metaseo", metaseo);
		try {
			request.getRequestDispatcher("/templates/" + config.getTemplate() + "/pages/category.jsp").forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
}
